package com.example.springboot_code_read.beandifinition;

import com.example.springboot_code_read.bean.MyBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;

import java.io.IOException;

public class BeanDefinitionTest {

    public static void main(String[] args) throws IOException {

        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        factory.registerBeanDefinition("myBean", createMyBean());

        MyBean myBean = factory.getBean("myBean", MyBean.class);

        System.out.println(myBean);

        factory.destroySingleton("myBean");

    }

    private static BeanDefinition createMyBean() throws IOException {

        SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
        MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(MyBean.class.getName());

        ScannedGenericBeanDefinition scannedGenericBeanDefinition = new ScannedGenericBeanDefinition(metadataReader);
        scannedGenericBeanDefinition.setScope("singleton");
        scannedGenericBeanDefinition.setLazyInit(true);
        scannedGenericBeanDefinition.setPrimary(true);
        scannedGenericBeanDefinition.setAbstract(false);
        scannedGenericBeanDefinition.setInitMethodName("init");
        scannedGenericBeanDefinition.setDestroyMethodName("destroy");
        scannedGenericBeanDefinition.setAutowireCandidate(true);
        scannedGenericBeanDefinition.setRole(BeanDefinition.ROLE_APPLICATION);
        scannedGenericBeanDefinition.setDescription("This is a custom bean definition");
        scannedGenericBeanDefinition.setResourceDescription("com.example.springboot_code_read.beandifinition.BeanDefinitionTest");
        scannedGenericBeanDefinition.getPropertyValues().add("id", "1");
        scannedGenericBeanDefinition.getPropertyValues().add("name", "xiaomi");

        return scannedGenericBeanDefinition;
    }

}
